package com.ruoyi.wechat.config;

import com.ruoyi.wechat.common.Constants;
import com.ruoyi.wechat.utils.LoginHelper;
import com.ruoyi.wechat.utils.PageHelper;
import org.springframework.util.ObjectUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 请求过滤器
 * </p>
 *
 * @author YinHeng
 * @since 2024/2/25
 */
public class RequestFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        //设置分页信息
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");
        if (!ObjectUtils.isEmpty(pageNum)) {
            // 设置当前页和页面尺寸到线程变量
            PageHelper.setPageNum(Integer.valueOf(pageNum));
        }
        if (!ObjectUtils.isEmpty(pageSize)) {
            PageHelper.setPageSize(Integer.valueOf(pageSize));
        }

        String token = httpRequest.getHeader(Constants.Login.AUTH_HEARD);

        //如果存在口令，则设置当前口令
        if (token != null && !token.isEmpty()) {
            try {
                LoginHelper.setToken(token);
                chain.doFilter(request, response);
            } finally {
                LoginHelper.removeToken();
            }
        } else {
            chain.doFilter(request, response);
        }
    }
}
